package com.ruoyi.common.utils.bean;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtils implements ApplicationContextAware {

    /**
     * 上下文实例
     */
    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext(){
        //判断是否为null
        if(applicationContext == null){
            throw new IllegalStateException("applicationContext未注入，请在applicationContext.xml中定义ApplicationContextHolder.");
        }
        return applicationContext;
    }

    /**
     * 通过name获取bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取bean
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T getBean(Class<T> clazz ){
        System.out.println("clazz:"+clazz);
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过 class和name获取bean
     * @param clazz
     * @param name
     * @return
     * @param <T>
     */
    public static <T> T getBean(Class<T> clazz,String name){
        return getApplicationContext().getBean(name,clazz);
    }

}
